//
//  SendEmailToOwnerViewController.swift
//  ezyform
//
//  Created by MoennigQ on 26/3/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
class SendEmailToOwnerViewController: BaseViewController {
    var timer : Timer?
    var model: PVDDetailModel!
    var customView = SendEmailToOwnerView()
    var countDownKey: String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        initUI()
    }
    
    func initUI(){
        self.customView.setTitleInfo(R.string.localizable.sendWebSign())
        self.view = self.customView
        self.customView.setData(self.model)
        
        self.customView.sendBtn.addTarget(self, action: #selector(sendBtnClick), for: UIControl.Event.touchUpInside)
        
        self.countDownKey = JobDetailModelHelper.shared.jobDetailModel.id + "ForSendEmail"
        self.customView.emailKey = JobDetailModelHelper.shared.jobDetailModel.id + "ForSendEmailEmail"
        self.customView.ownerNameKey = JobDetailModelHelper.shared.jobDetailModel.id + "ForSendEmailOwnerName"
        self.getCurrentTimeForCountDown()
    }
    @objc
    func sendBtnClick(){
        if Connectivity.isConnectedToInternet {
            let email = self.customView.emailTextfield.textField.text!.trimmingCharacters(in: .whitespaces)
            let ownerName = self.customView.nameTextfield.textField.text!.trimmingCharacters(in: .whitespaces)
            let vc = JobDetailService()
            vc.setBlockAfterNetwork({ (result , _) in
                ModelViewUtil.shared.hideLoadingView()
                //show deleted toast
                self.saveCurrentTimeForCountDown()
                MBProgressHUD.showToast(parentView: self.view, text: R.string.localizable.messageSent())
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    self.navigationController?.popViewController(animated: false)
                }
            }) { (code,msg) in
                ModelViewUtil.shared.hideLoadingView()
                Tool().showErrorInfo(code,msg)
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView(R.string.localizable.sendingEmail())
            vc.sendEmailToOwner(ownerName, email: email)
        }else{
            Tool().showFailureInfo()
        }
    }
    func getCurrentTimeForCountDown(){
        if let dateStr = UserDefaults.standard.object(forKey: self.countDownKey) as? String {
            //resend是默认上次的信息
            self.customView.setDefaultInfo()
            
            let dateFormatter = DateFormatter()
            let locale = Locale(identifier: "en-au")//en是语言码，au是地区码，覆盖设备上语言和地区的设置
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            dateFormatter.locale = locale
            if let beginDate = dateFormatter.date(from: dateStr) {
                let components = Calendar.current.dateComponents([.second], from: beginDate, to: Date())
                if let toNowSecond = components.second, toNowSecond < APPConfig.SignatureResendEmailToOwnerInterval {
                    self.customView.countDownSeconds = APPConfig.SignatureResendEmailToOwnerInterval - toNowSecond
                    self.startTimer()
                }else{
                    //有UserDefaults.standard.object(forKey: self.countDownKey)标识发送过，按钮显示为resend
                    self.customView.setResendInfo()
                }
            }
        }
    }
    func saveCurrentTimeForCountDown(){
        let dateFormatter = DateFormatter()
        let locale = Locale(identifier: "en-au")//en是语言码，au是地区码，覆盖设备上语言和地区的设置
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = locale
        let currentDateStr = dateFormatter.string(from: Date())
        UserDefaults.standard.set(currentDateStr, forKey: self.countDownKey)
        //保存email，name，用于resend设置
        if let data = self.customView.emailTextfield.textField.text {
            UserDefaults.standard.set(data, forKey: self.customView.emailKey)
        }
        if let data = self.customView.nameTextfield.textField.text {
            UserDefaults.standard.set(data, forKey: self.customView.ownerNameKey)
        }
    }
    
    @objc func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(resendCountDown), userInfo: nil, repeats: true)
        //调用fire()会立即启动计时器
        timer!.fire()
    }
    @objc func stopTimer() {
        if timer != nil {
            timer!.invalidate() //销毁timer
            timer = nil
        }
    }
    @objc func resendCountDown(){
        self.customView.refreshCountDown()
        if self.customView.countDownSeconds == 0 {
            self.stopTimer()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
